<template>
   <div>
    <div class="search">
      <input type="text" v-model="keyword" class="search-input" placeholder="输入城市名或拼音">
    </div>
    <!-- 输入框为空不显示 -->
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li class="search-item border-bottom"
        v-for="item in list" :key="item.id"
        @click="handleCityClick(item.name)">{{item.name}}</li>
        <!-- 返回列表没有数据时显示该信息 -->
        <!-- TIPS:模板写样式,js写逻辑 -->
        <li class="search-item border-bottom" v-show="hasNoData">当前未找到该城市</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  data () {
    return {
      keyword: '',
      // 返回给输入框下面的div的内容
      list: [],
      timer: null
    }
  },
  methods: {
    ...mapMutations(['localCity']),
    // 改变当前城市
    handleCityClick (city) {
      this.localCity(city)
      // this.$store.commit('localCity', city)
      // router 编程式跳转页面
      this.$router.push('/')
    }
  },
  computed: {
    // 计算数据列表长度
    hasNoData () {
      return !this.list.length
    }
  },
  props: {
    // A-Z列表
    cities: Object
  },
  // 页面渲染完毕时-生命周期钩子
  mounted () {
    // 调用滑动控件实现当数据成功加载还可以滑动
    // 参数必须是dom节点或结构
    this.Bscroll = new Bscroll(this.$refs.search)
  },
  watch: {
    // keyword改变调取相应内容
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      // 输入框没有内容返回空,数据列表不存在
      if (!this.keyword) {
        this.list = []
        return
      }
      // keyword发生改变 延迟100毫秒执行函数
      this.timer = setTimeout(() => {
        const result = []
        // 循环cities列表的每一项内容
        for (var i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        this.list = result
      }, 100)
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~stylus/varibles.styl'
  .search
    height: .72rem
    padding: 0 .1rem
    background: $bgColor
    .search-input
      width: 100%
      height: .62rem
      line-height: .62rem
      text-align: center
      border-radius: .06rem
      color: #666
      box-sizing: border-box
      // 两边加点边距
      padding: 0 .2rem
  .search-content
    z-index: 1
    overflow: hidden
    position: absolute
    top: 1.58rem
    left: 0
    right: 0
    bottom: 0
    background: #eee
    .search-item
      line-height: .62rem
      // 距离左边位置
      padding-left: .2rem
      background: #fff
      color: #666
</style>
